#!/usr/bin/env python
import os
import sys

# Log errors.
def log_exception(*args, **kwds):
  """Function used for logging exceptions.
  """
  import logging
  logging.exception('Exception in request:')


def main():
  HERE = os.path.abspath(__file__)
  HERE = os.path.join(os.path.dirname(HERE), '..')
  HERE = os.path.normpath(HERE)

#  WERKZEUG = [os.path.join(HERE, 'werkzeug')]
  DJANGO_EXTENSIONS = [os.path.join(HERE, 'django_extensions')]
  DJANGO = [os.path.join(HERE, 'django')]
  EE = [os.path.join(HERE, 'EE_django', 'EE')]
  #PIL = [os.path.join(HERE, 'PIL')]
  #if os.name == 'posix':
  #  VTK = []
  #else:
  #  VTK = [os.path.join(HERE, 'VTK', 'lib', 'site-packages')]
  
  #sys.path = VTK + PIL + WERKZEUG + DJANGO_EXTENSIONS + DJANGO + CASAM + sys.path
  sys.path = DJANGO_EXTENSIONS + DJANGO + EE + sys.path

  #print sys.path
  if len(sys.argv) == 1:
    sys.argv += ['runserver']

  import manage
  manage.main()

  from django.contrib.auth.models import Group
  try:
    gr1 = Group.objects.get(name='Beheerder')
  except Group.DoesNotExist:
    gr1 = Group(name='Beheerder')
    gr1.save()
    gr2 = Group(name='Groep')
    gr2.save()
    gr3 = Group(name='Leraar')
    gr3.save()
	
  from EE.models import Windmill
  mill1 = Windmill(name='E-33', diameter=33, capacity=3, cost=2000000)
  mill1.save()
  mill2 = Windmill(name='E-40', diameter=44, capacity=5, cost=3500000)
  mill2.save()
  
  from EE.models import Contract
  contract1 = Contract(noOfCitizens=75000, usage=75, price=100)
  contract1.save()
  contract2 = Contract(noOfCitizens=50000, usage=50, price=100)
  contract2.save()
  contract3 = Contract(noOfCitizens=25000, usage=25, price=100)
  contract3.save()
  contract4 = Contract(noOfCitizens=100000, usage=100, price=100)
  contract4.save()
  contract5 = Contract(noOfCitizens=10000, usage=10, price=100)
  contract5.save()

  from django.conf import settings
  settings.DEBUG = True

  import django.core.signals

  # Log all exceptions detected by Django.
  django.core.signals.got_request_exception.connect(log_exception)


if __name__ == '__main__':
  main()
